package com.itheima.reggie.controller;

import com.itheima.reggie.ReggieApp;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.images}")
    private String basePath;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws FileNotFoundException {
        //file是一个临时文件,需要转存到指定位置,否则本次请求完成后临时文件会删除
        log.info("file:{}", file);
        //获取原文件后缀名
        //String originalFilename = file.getOriginalFilename();
        //String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        //log.info("文件后缀名:{}", suffix);
        //使用UUID生成文件名防止名字重复,导致文件被覆盖
        //String fileName = UUID.randomUUID() + suffix;
        String fileName = UUID.randomUUID() + "";
        log.info("生成的文件名:{}", fileName);
        //jar包路径使用
        //ApplicationHome h = new ApplicationHome(ReggieApp.class);
        //File jarF = h.getSource();
        //String jarpath = jarF.getParentFile().toString();
        //File path = new File(jarpath, basePath);
        //判断目录是否存在
        File path = new File(basePath);
        if (!path.exists()) {
            //创建目录
            path.mkdirs();
        }
        try {
            file.transferTo(new File(path, fileName));
            redisTemplate.opsForSet().add("set1",fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载回显文件
     *
     * @param response
     * @param name
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) {
        try {
            //设置响应类型
            response.setContentType("image/jpeg");

            //jar包路径使用
            //ApplicationHome h = new ApplicationHome(ReggieApp.class);
            //File jarF = h.getSource();
            //String jarpath = jarF.getParentFile().toString();
            //File path = new File(jarpath, basePath);

            File path = new File(basePath);
            FileInputStream fis = new FileInputStream(new File(path, name));
            ServletOutputStream os = response.getOutputStream();
            /*byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }*/
            IOUtils.copy(fis, os);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
